﻿using Common.Helpers;
using Common.HttpApis;
using GptChatBatch.WinUI.Models;
using GptChatBatch.WinUI.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GptChatBatch.WinUI.Forms
{
    public partial class FrmChatGptBatch : Form
    {
        public FrmChatGptBatch()
        {
            InitializeComponent();
           
        }
             
        private void FrmChatGptBatch_Load(object sender, EventArgs e)
        {
            txtOutDir.Text = Environment.CurrentDirectory;
            dtpSubDir.Value = DateTime.Now.AddDays(1);
            dgvList.AutoGenerateColumns = false;
            dgvList.DataSource= new List<Article>();
            refreshTpls();
        }

        private void btnSelectOutDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.SelectedPath = Environment.CurrentDirectory;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string folderPath = folderBrowserDialog.SelectedPath;
                txtOutDir.Text = folderPath;               
            }
        }

        private void btnSelectPath_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "文本文件|*.txt|csv文件|*.csv";
            fileDialog.InitialDirectory = Environment.CurrentDirectory;
            if (fileDialog.ShowDialog()==DialogResult.OK)
            {
                string filePath= fileDialog.FileName;               
                List<Article> articles = new List<Article>();
                string ext = Path.GetExtension(filePath);
                if (ext == ".csv")
                {
                    DataTable dataTable = CsvHelper.Parse(filePath);
                    foreach (DataRow row in dataTable.Rows)
                    {
                        string title = row["title"].ToString();
                        //string file = row["filePath"].ToString();
                        //articles.Add(new Article { Title = title, FilePath = file });  
                        articles.Add(new Article { Title = title});

                    }
                }
                else if(ext == ".txt")
                {
                    string[] titles=File.ReadAllLines(filePath);
                    foreach (string title in titles)
                    {                     
                        articles.Add(new Article { Title = title.Trim(),  });
                       
                    }
                }
                
                dgvList.DataSource = articles;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //List<Article> articles = (List<Article>)dgvList.DataSource;
            //string[] titleList = rtxtTiltleList.Lines.Select(s);
            List<string> titleList=new List<string>();
            foreach(var item in rtxtTiltleList.Lines)
            {
                if(!string.IsNullOrEmpty(item.Trim()))
                    titleList.Add(item.Trim());
            }

            //List<Article> articles = (List<Article>)dgvList.DataSource;
            if (titleList.Count == 0)
            {
                MessageBox.Show("请导入需要的文章标题");
                return;
            }
            //string[] titles = articles.Select(p => p.Title).ToArray(); //{ "光学和波动速度的琐碎原理", "感受到物理学动力的力量" };
            string[] titles = titleList.ToArray();
            //清空日志
            txtLog.Text = "";
            btnStart.Enabled = false;
            string tplName = cmbTpl.SelectedValue.ToString().Trim();
            Task.Run(() => {

                foreach (string title in titles) 
                {
                    GernerateFile(title,tplName);
                }
                this.Invoke(new Action(() =>
                {                    
                    txtLog.AppendText("文章已全部生成完成\r\n");
                    btnStart.Enabled = true;
                    MessageBox.Show("文章已全部生成完成");
                }));
            });
        }

        private void GernerateFile(string title, string tplName)
        {
            string tpl = txtQuestionTpl1.Text.Trim();            
            string date=dtpSubDir.Text.Trim();
            string outputDir = txtOutDir.Text.Trim();

            if (cbCanTplSubDir.Checked)
            {
                outputDir = Path.Combine(outputDir, tplName);
                //确保目录存在
                if (!Directory.Exists(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }
            }
            if (cbCanDateSubDir.Checked)
            {
                outputDir = Path.Combine(outputDir, date);
                //确保目录存在
                if (!Directory.Exists(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }
            }                                      
            try
            {
                //打印日志
                this.Invoke(new Action(() =>
                {
                    txtLog.AppendText("正在生成文章：" + title + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
                }));

                //第一个问题
                string question = tpl.Replace("{title}", title);
                string filePath = Path.Combine(outputDir, title + ".firsttxt");
                askChatGptOne(question,filePath);
                //第2个问题
                question = txtQuestionTpl2.Text.Trim();
                if (!string.IsNullOrEmpty(question))
                {
                    filePath = Path.Combine(outputDir, title + ".sencondtxt");
                    askChatGptOne(question, filePath);
                }
                //第3个问题
                question = txtQuestionTpl3.Text.Trim();
                if (!string.IsNullOrEmpty(question))
                {
                    filePath = Path.Combine(outputDir, title + ".threetxt");
                    askChatGptOne(question, filePath);
                }               
                //第4个问题
                question = "非常好，请给我取5个非常具有吸引力的标题";
                filePath = Path.Combine(outputDir, title + ".firsttitle");
                askChatGptOne(question, filePath);
                //第5个问题
                question = "不够有吸引力";
                filePath = Path.Combine(outputDir, title + ".sencondtitle");
                askChatGptOne(question, filePath);

                //打印日志
                this.Invoke(new Action(() =>
                {
                    txtLog.AppendText("已经生成文章：" + title + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
                }));
            }
            catch (Exception err)
            {
                Log4Helper.Error(err.Message);
                this.Invoke(new Action(() =>
                {
                    rtxtOutput.AppendText("答：" + "出错了,"+err.Message + "\r\n");
                    //rtxtOutput.ScrollToCaret();
                    txtLog.AppendText("出错了,文章：" + title + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
                }));

            }

        }

        private void askChatGptOne(string question,string filePath)
        {
            string userId = txtUserId.Text.Trim();
            //string input = $"我是心理学作家，请帮我要写一篇文章，以”{title}“为题，要求字数9000字左右，文章风格为武侠风格，内容积极向上，偏向阿德勒心理学派的观点，开头要足够吸引人";               
            ChatGptHttp chatGptHttp = new ChatGptHttp { prompt = question, userId = userId };
            //string data = "{\"prompt\":\""+ input + "\",\"userId\":\"#/chat/1685099056344\",\"network\":true,\"system\":\"\",\"withoutContext\":false,\"stream\":false}"; ;
            string data = JsonConvert.SerializeObject(chatGptHttp);
            //输入          
            this.Invoke(new Action(() =>
            {                
                rtxtOutput.AppendText("问：" + question + "\r\n");
                rtxtOutput.ScrollToCaret();
            }));
            //处理
            string output = ChatGptHttp.Post(data);//不要放在invoke里面，否则会阻塞
            //输出
            this.Invoke(new Action(() =>
            {                             
                rtxtOutput.AppendText("答：" + output + "\r\n");
                rtxtOutput.ScrollToCaret();               
             
                if (cbCan2Line.Checked)
                {
                    //留空行就是原始输出
                }
                else
                {
                    output = output.Replace("\n\n", "\n");
                }
                File.WriteAllText(filePath, output);
            }));
         
        }

        private void btnOpenDir_Click(object sender, EventArgs e)
        {
            string folderPath=txtOutDir.Text.Trim();
            if (!string.IsNullOrEmpty(folderPath))
            {
                OpenFolderInFileExplorer(folderPath);
            }
            
        }
        private void OpenFileLocation(string filePath)
        {
            Process.Start("explorer.exe", $"/select,\"{filePath}\"");
        }
        private void OpenFolderInFileExplorer(string folderPath)
        {
            Process.Start("explorer.exe", folderPath);
        }

        private void btnAddTpl_Click(object sender, EventArgs e)
        {
            string tplName = cmbTpl.Text.Trim();
            string question1 = txtQuestionTpl1.Text.Trim();
            string question2 = txtQuestionTpl2.Text.Trim();
            string question3 = txtQuestionTpl3.Text.Trim();

            if (string.IsNullOrEmpty(tplName))
            {
                return;
            }
            QuestionTplService tplService= new QuestionTplService();
            tplService.Add(new QuestionTpl { TplName = tplName, Question1 = question1, Question2 = question2, Question3 = question3 });
            refreshTpls();
            loadTpl();
        
        }


        private void btnRefreshTpl_Click(object sender, EventArgs e)
        {
            refreshTpls();
            loadTpl();
        }

        private void refreshTpls()
        {
            QuestionTplService tplService = new QuestionTplService();
            List<QuestionTpl> questionTpls = tplService.GetList();
            cmbTpl.DataSource = questionTpls;
            cmbTpl.DisplayMember = "TplName";
            cmbTpl.ValueMember = "TplName";
        }

        private void cmbTpl_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadTpl();
        }

        private void loadTpl()
        {
            QuestionTpl questionTpl = (QuestionTpl)cmbTpl.SelectedItem;
            txtQuestionTpl1.Text = questionTpl.Question1;
            txtQuestionTpl2.Text = questionTpl.Question2;
            txtQuestionTpl3.Text = questionTpl.Question3;
        }

        private void btnModifyTpl_Click(object sender, EventArgs e)
        {
            QuestionTpl selQuestionTpl = (QuestionTpl)cmbTpl.SelectedItem;
            string tplName = selQuestionTpl.TplName;
            string question1 = txtQuestionTpl1.Text.Trim();
            string question2 = txtQuestionTpl2.Text.Trim();
            string question3 = txtQuestionTpl3.Text.Trim();

            if (string.IsNullOrEmpty(tplName))
            {
                return;
            }
            QuestionTplService tplService = new QuestionTplService();
            tplService.Modify(new QuestionTpl { TplName = tplName, Question1 = question1, Question2 = question2, Question3 = question3 });
            refreshTpls();
            loadTpl();
        }

        private void btnDeleteTpl_Click(object sender, EventArgs e)
        {
            QuestionTpl selQuestionTpl = (QuestionTpl)cmbTpl.SelectedItem;
            string tplName = selQuestionTpl.TplName;
            QuestionTplService tplService = new QuestionTplService();
            tplService.Delete(tplName);
            refreshTpls();
            loadTpl();
        }

        private void btnClearList_Click(object sender, EventArgs e)
        {
            dgvList.DataSource=new List<Article>();
        }

        private void dgvList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.V)
            {
                string[] rowCells = Clipboard.GetText().Split('\n');
                //List<Article> list = new List<Article>();
                List<Article> list = (List<Article>)dgvList.DataSource;
                dgvList.DataSource = null;
                foreach (string cell in rowCells)
                {
                    if (!string.IsNullOrEmpty(cell))
                    {
                        string[] values = cell.Split('\t');
                        Article article= new Article() { Title = values[0].ToString() };
                        list.Add(article);
                    }
                }
                
                dgvList.DataSource = list;

                //dgvList.DataSource=list;
                // 获取当前选中单元格的位置
                //int currentRowIndex = dgvList.SelectedCells[0].RowIndex;
                //int currentColumnIndex = dgvList.SelectedCells[0].ColumnIndex;

                //foreach (string cell in rowCells)
                //{
                //    if (!string.IsNullOrEmpty(cell))
                //    {
                //        string[] values = cell.Split('\t');

                //        for (int i = 0; i < values.Length; i++)
                //        {
                //            // 确保列的索引不会超出范围
                //            if (currentColumnIndex + i < dgvList.Columns.Count &&
                //                currentRowIndex < dgvList.Rows.Count)
                //            {
                //                DataGridViewCell selectedCell = dgvList.Rows[currentRowIndex].Cells[currentColumnIndex + i];
                //                selectedCell.Value = values[i];
                //            }
                //        }

                //        currentRowIndex++;
                //    }
                //}
            }
        }
    }
}
